import sys
import os
import datetime
import arcpy

def log(message):
    time_stamp = datetime.datetime.now().strftime('%x %X')
    full_message = "{0} - {1}".format(time_stamp, message)
    print full_message
    log_file = open(os.path.join(os.path.curdir, "Swsp.Build.log"), 'a')
    log_file.write(full_message + "\n")
    log_file.close()

def publish(sourcePath, destPath):
    if arcpy.Exists(destPath):
        log("Deleting existing published data...")
        ds = arcpy.Delete_management(destPath)
        log("Deleted: {0}".format(ds))

    log("Publishing from {0}...".format(sourcePath))
    nodes_sde = arcpy.Copy_management(sourcePath, destPath)
    log("Published to: {0}".format(destPath))

try:
    # Source paths
    source_dir = r'\\ws18325\Stormwater D\RiskModel\RiskAssessment\WaterQuality'
    source_gdb = os.path.join(source_dir, 'WQRiskNetwork.gdb')

    # Connect to SWSP SDE database
    script_dir = os.path.dirname(os.path.abspath(__file__))
    sde_path = os.path.join(script_dir, "BESDBPROD1.SWSP_RAWQ.GIS.sde")
    arcpy.env.workspace = sde_path

    base_nodes_sde_path = os.path.join(sde_path, "SWSP_RAWQ.GIS.swsp_wqnodes_base")
    base_nodes = os.path.join(source_gdb, "WQNodes_base")
    publish(base_nodes, base_nodes_sde_path)

    base_conveyance_sde_path = os.path.join(sde_path, "SWSP_RAWQ.GIS.swsp_wqnodes_base")
    base_conveyance = os.path.join(source_gdb, "WQNodes_base")
    publish(base_conveyance, base_conveyance_sde_path)

    net_nodes_sde_path = os.path.join(sde_path, "SWSP_RAWQ.GIS.swsp_wqnodes_net")
    net_nodes = os.path.join(source_gdb, "WQNodes_net")
    publish(net_nodes, net_nodes_sde_path)

    net_conveyance_sde_path = os.path.join(sde_path, "SWSP_RAWQ.GIS.swsp_wqnodes_net")
    net_conveyance = os.path.join(source_gdb, "WQNodes_net")
    publish(net_conveyance, net_conveyance_sde_path)

except arcpy.ExecuteError:
    log(arcpy.GetMessages(2))
    sys.exit()
except Exception as e:
    log("Error: {0}".format(e.message))
    sys.exit()
finally:
    log("Publishing water quality results complete.")
